package com.longshanks.retrorally; 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Environment;
import android.util.Log;

public class FileManager {
	
	public static final String TAG = FileManager.class.getSimpleName();
	
	public static final String DB_NAME = "RetroRally.db";

	public static final String EXTERNAL_STORAGE = Environment.getExternalStorageDirectory().getPath();

	private static FileManager fileManager = null;

	private String dbPath = null;

	private String unencryptedDbPath = null;

	private FileManager() {

		dbPath = EXTERNAL_STORAGE + "/Android" + Environment.getDataDirectory() + "/" + "com.longshanks.retrorally"
				+ "/databases/" + DB_NAME;
	}

	public static FileManager getInstance() {
		if(fileManager == null) {
			fileManager = new FileManager();
		}
		return fileManager;
	}

	public void copyFile(File origFile, File newFile) throws IOException {
		if(origFile == null || newFile == null) {
			throw new IllegalArgumentException("origFile and/or newFile cannot be null");
		}
		if(newFile.exists()) {
			newFile.delete();
		}
		else if(newFile.getParentFile() != null) {
			newFile.getParentFile().mkdirs();
		}

		Log.d(TAG, "Copying file to " + newFile.getPath());

		FileInputStream myInput = null;
		FileOutputStream myOutput = null;
		
		try {
			myInput = new FileInputStream(origFile);
			myOutput = new FileOutputStream(newFile);

			byte[] buffer = new byte[1024];
			int length;
			while((length = myInput.read(buffer)) > 0) {
				myOutput.write(buffer, 0, length);
			}
			myOutput.flush();

		} catch(IOException ioe) {
			Log.e("error", ioe.toString());
			if(newFile.exists()) {
				newFile.delete();
			}
			try {
				myOutput.close();
				myInput.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		} 

	}

	public boolean isExternalStorageWritable() {

		String externalStorageState = Environment.getExternalStorageState();

		return externalStorageState.equalsIgnoreCase(Environment.MEDIA_MOUNTED)
				|| externalStorageState.equalsIgnoreCase(Environment.MEDIA_CHECKING)
				|| externalStorageState.equalsIgnoreCase(Environment.MEDIA_SHARED);
	}

	public String getDatabasePath() {
		return dbPath;
	}

	public String getUnencryptedDatabasePath() {
		return unencryptedDbPath;
	}
}
